import zipfile
import sqlite3
from reedsolo import RSCodec ,ReedSolomonError
from tqdm import tqdm #tqdm
import base64
import logging
import pprint
from hashlib import blake2b as hash_
from inc import *

# alter table main.hash add column t
# ALTER TABLE main.hash ADD COLUMN timestamp

class upgrade():
    def __init__(self,dbpath):
        self.db=sqlite3.connect(dbpath,check_same_thread=False)
        self.cur=self.db.cursor()
        self.verList=[0,1]
        self.ver=self.checkVer()
        if(not self.up()) :
            logging.error("升级失败！")
    def __del__(self):
        logging.info(f"upgrade __del__")
        self.db.close()
    def checkVer(self):
        resute=self.cur.execute("select name from sqlite_master where type=\'table\' and name=\'config\' ;")
        resute=resute.fetchall()
        if(len(resute)==0):
            return 0
        else:
            resute=self.cur.execute("SELECT val FROM config WHERE key='ver';")
            resute=resute.fetchone()
            return resute[0]
    def tryjs(self,sql):
        try:
            if(type(sql)==str):
                self.db.execute(sql)
            if(type(sql)==list):
                for s in sql:
                    self.db.execute(s)
        except (sqlite3.Error, Exception) as e:
            logging.error(f"Database error: {e}\nsql:{sql}")
            self.db.rollback()
            return False
        else:
            self.db.commit()
            return True
    def up(self):
        if(self.ver==0):
            sql=[
                "CREATE TABLE \"config\" (\"key\"  TEXT NOT NULL,\"val\"  TEXT,PRIMARY KEY (\"key\"));",
                "INSERT INTO \"config\" (\"key\", \"val\") VALUES (\'ver\', 0);",
                "ALTER TABLE main.checks ADD COLUMN timestamp INTEGER;",
                "UPDATE \"config\" SET \"val\"=1 WHERE (\"key\"=\'ver\')",
                "SELECT	list.path, checks.hash, checks.timestamp FROM list LEFT JOIN checks ON checks.path = list.path ;"

            ]
            if(not self.tryjs(sql)) : return False
            logging.warning("Successfully upgraded to 1")
            self.ver=1
        if(self.ver ==1 ):
            pass
        return True
if __name__ == "__main__":
    import easygui
    logging.basicConfig(level=logging.INFO)
    BackupFileSize=10
    dbpath=easygui.fileopenbox()
    upgrade(dbpath)